package kr.hkit.powerjava.chapter24.work;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class StudentDao implements InterfaceDao<Student> {

	private ArrayList<Student> list;
	private final static String FILE_NAME = "testStdList.data";
	@Override
	public void insertData(Student item) {
		if(!list.contains(item)){
			list.add(item);
		}else{
			System.out.println("중복된 데이터");
		}
	}

	@Override
	public void deleteData(Student item) {
		list.remove(item);
	}

	@Override
	public void updateData(Student item) {
		list.set(list.indexOf(item), item);

	}

	@Override
	public Student searchData(Student item) {
		return list.get(list.indexOf(item));
	}

	@Override
	public void prnData(Comparator<Student> comp) {
		if (comp == null){
			Collections.sort(list);
		}else{
			Collections.sort(list, comp);
		}
		for (Student std : list){
			System.out.println(std);
		}
	}

	@Override
	public void loadFile() {
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(StudentDao.FILE_NAME)));
			list = ((ArrayList<Student>) ois.readObject());
		} catch (FileNotFoundException e) {
			try {
				new File(StudentDao.FILE_NAME).createNewFile();
			} catch (IOException e1) {}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(ois!=null)try{ois.close();}catch(Exception e){}
		}

	}

	@Override
	public void saveFile() {
		ObjectOutputStream oos = null;
		
		try {
			oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(StudentDao.FILE_NAME)));
			oos.writeObject(list);
		}catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(oos != null)try{oos.close();}catch(Exception e){}
		}
	}
}
